package com.tsfyun.scm.gateway.config;

import com.tsfyun.scm.gateway.filter.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.validation.Validator;

import java.util.List;

/**
 * @Description:
 * @CreateDate: Created in 2021/6/28 10:04
 */
@Configuration
@Import(value = {GatewayExceptionConfig.class})
public class GatewayConfig {

    /**
     * 频繁检查
     * @return
     */
    @Bean
    public GlobalFilter frequencyCheckFilter(){
        return new FrequencyCheckFilter();
    }

    /**
     * 白名单
     * @return
     */
    @Bean
    @ConditionalOnProperty(name = "gateway.ipcheck.open",havingValue = "true")
    public GlobalFilter iPWhiteCheckFilter(){
        return new IPWhiteCheckFilter();
    }

    /**
     * 请求过滤
     * @return
     */
    @Bean
    public GlobalFilter requestFilter(){
        return new RequestFilter();
    }

    /**
     * 响应过滤
     * @return
     */
    @Bean
    public GlobalFilter responseFilter(){
        return new ResponseFilter();
    }


    /**
     * 限流器
     * @param redisTemplate
     * @param script
     * @param validator
     * @return
     */
    @Bean
    @Primary
    @ConditionalOnMissingBean
    CustomRedisRateLimiter customRedisRateLimiter(
            ReactiveRedisTemplate<String, String> redisTemplate,
            @Qualifier(CustomRedisRateLimiter.REDIS_SCRIPT_NAME) RedisScript<List<Long>> script,
            Validator validator){
        return new CustomRedisRateLimiter(redisTemplate , script , validator);
    }

}
